import { Form, Input, Button, message } from 'antd';
import { apiLogin, apiGiteeLogin } from '../api'
import Cookie from 'js-cookie'
import React, { useEffect } from 'react'
import { useLocation } from 'react-router-dom'

const Login = () => {

    const location = useLocation();

    // 在页面初始化的时候
    useEffect(() => {
        // 判断地址栏参数 是否存在code
        if (location.search) {
            const code = location.search.replace('?code=', "")

            // 第三方登录的请求
            apiGiteeLogin({ code }).then((res: any) => {
                // 将token 保存到本地
                Cookie.set('token', res.token)

                // 提示用户登录成功
                message.success('登录成功')

                // 跳转页面
                window.location.href = '/'
            })
        }

    }, [])



    // 登录 提交
    const onFinish = (data: { password: string, username: string }) => {
        apiLogin(data).then((res: any) => {
            // 将token 保存到本地
            Cookie.set('token', res.token)

            // 提示用户登录成功
            message.success('登录成功')

            // 跳转页面
            window.location.href = '/'

        })
    }

    const toGiteeLogin = () => {
        // 将用户引导到第三方认证页面
        window.location.href = 'https://gitee.com/oauth/authorize?client_id=e58e7fa36aeb6a570472505607bc916bc7bc0f8b5f94edb0e4b74989ce69c0d4&redirect_uri=http://10.1.235.21:3000/login&response_type=code'
    }

    return <div>
        <Form
            name="basic"
            onFinish={onFinish}
            autoComplete="off"
        >
            <Form.Item
                label="用户名"
                name="username"
                rules={[{ required: true, message: 'Please input your username!' }]}
            >
                <Input />
            </Form.Item>

            <Form.Item
                label="密码"
                name="password"
                rules={[{ required: true, message: 'Please input your password!' }]}
            >
                <Input.Password />
            </Form.Item>

            <Form.Item>
                <Button type="primary" htmlType="submit">
                    登录
                </Button>
                <Button onClick={toGiteeLogin} > gitee 登录 </Button>
            </Form.Item>
        </Form>
    </div>
}

export default Login